from flask import Blueprint, render_template, jsonify, request
from flask_login import login_required, current_user
from applications.common.utils.rights import authorize
from applications.models import Tag
from applications.schemas import TagSchema
from sqlalchemy import desc
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.curd import get_one_by_id
from applications.common.utils.validate import str_escape
from applications.extensions import db
import datetime

bp = Blueprint('tag', __name__, url_prefix='/tag')


# 首页
@bp.get('/')
def index():
    user = current_user
    return render_template('blog/tag/main.html', user=user)

# 资源数据
@bp.get('/data')
# @authorize("blog:tag:main")
def data():
    limit = str_escape(request.args.get('limit', type=int))
    type = str_escape(request.args.get('type', type=str)) or ""
    if int(limit) > 1000 or int(limit) < 0:
        limit = 100
    tag_name = str_escape(request.args.get('tagName', type=str))
    filters = []
    if tag_name:
        filters.append(Tag.name.contains(tag_name))
    tags = Tag.query.filter(*filters).order_by(desc(Tag.id)).layui_paginate()
    return table_api(data=TagSchema(many=True).dump(tags), count=tags.total,limit=limit)


# 资源删除
@bp.delete('/remove/<int:id>')
@authorize("blog:tag:remove", log=True)
def remove(id):
    r = Tag.query.filter_by(id=id).update({"is_del": 1})
    db.session.commit()
    if not r:
        return fail_api(msg="资源删除失败")
    return success_api(msg="资源删除成功")


#资源增加
@bp.get('/add')
@authorize("blog:tag:add", log=True)
def add():
    return render_template('blog/tag/add.html')


# 角色增加
@bp.post('/save')
@authorize("blog:tag:add", log=True)
def save():
    req = request.get_json(force=True)
    name = str_escape(req.get("name"))
    tag = Tag(
        name=name,
        is_del=0
    )
    db.session.add(tag)
    db.session.commit()
    return success_api(msg="成功")


# 资源编辑
@bp.get('/edit/<int:id>')
@authorize("blog:tag:edit", log=True)
def edit(id):
    r = get_one_by_id(model=Tag, id=id)
    return render_template('blog/tag/edit.html', tag=r)


# 更新资源
@bp.put('/update')
@authorize("blog:tag:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    id = req_json.get("tagId")
    data = {
        "name": str_escape(req_json.get("tagName")),
        "is_del": str_escape(req_json.get("isDel"))
    }
    tag = Tag.query.filter_by(id=id).update(data)
    db.session.commit()
    if not tag:
        return fail_api(msg="更新资源失败")
    return success_api(msg="更新资源成功")
